package com.wangyi.im.interceptor;

import com.wangyi.im.utils.CheckSumUtil;
import com.wangyi.im.utils.RandomUtil;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class HeaderInterceptor implements Interceptor {

    private String appkey;

    private String appSecret;

    public HeaderInterceptor(String appkey, String appSecret){
        this.appkey = appkey;
        this.appSecret = appSecret;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Headers.Builder builder = request.headers().newBuilder();
        String nonce = RandomUtil.getRandomStr();
        String curTime = RandomUtil.getCurTime();
        String checkSum = CheckSumUtil.getCheckSum(appSecret, nonce, curTime);
        Headers headers = builder.add("Content-type","application/x-www-form-urlencoded;charset=utf-8")
                .add("appKey", appkey)
                .add("Nonce", nonce)
                .add("CurTime", curTime)
                .add("checkSum", checkSum)
                .build();
        return chain.proceed(request.newBuilder().headers(headers).build());
    }
}
